package com.aly.game.exe2lua.builder.impl;

import com.aly.game.exe2lua.Main;
import com.aly.game.exe2lua.builder.BaseExportBuilder;
import com.aly.game.exe2lua.enums.BuildType;
import com.aly.game.exe2lua.enums.ExportConfig;
import com.aly.game.exe2lua.funcs.TypeConsumer;
import com.aly.game.exe2lua.objs.*;
import com.aly.game.exe2lua.tool.JSON;
import com.aly.game.exe2lua.tool.CommonTool;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.Map;

/**
 * aly @ 16-11-12.
 */
public class LuaBuilder extends BaseExportBuilder {
    static final String ID_FIELD_NAME = "idx";

    public LuaBuilder(ExportConfig type) {
        super(type);
    }

    private static void buildStart(StringBuilder lineSb, BuildType buildType) {
        if (buildType == BuildType.many) {
            //start
            lineSb.append('{');
        }
    }

    private static void buildEnd(StringBuilder lineSb, BuildType buildType) {
        int i = lineSb.lastIndexOf(", ");
        if ((i + 2) == lineSb.length()) {
            lineSb.deleteCharAt(lineSb.lastIndexOf(","));
            lineSb.deleteCharAt(lineSb.lastIndexOf(" "));
        }
        if (buildType == BuildType.many) {
            lineSb.append('}');
        }
        lineSb.append(";\n");
    }

    static void parseLuaHead(String typeAlia, TypeConsumer consumer) {
        if (typeAlia.length() > 0) {
            String[] typeAndName = typeAlia.split(",");
            String type = typeAndName[0];
            String name;
            if (Main.clientDataFileNameFix.equals(type)) {
                name = type;
            } else {
                name = typeAndName.length > 1 ? typeAndName[1] : null;
            }
            consumer.onType(type, name);
        }
    }

    private void buildLienItem(StringBuilder lineSb, LineObj line, HeadItem item, BuildType buildType) {
        String funType = item.type;
        String cellVal = line.getValue(item);
        boolean buildMany = buildType == BuildType.many;
        if (cellVal.length() > 0) {
            if (funType.contains("json")) {
                if (buildMany) {
                    lineSb.append(item.filedName).append(" = ");
                }
                try {
                    Object m = JSON.parse(cellVal);
                    CommonTool.readObjec(lineSb, m);
                    lineSb.append(", ");
                } catch (Exception e) {
                    System.out.println("error json:" + cellVal);
                    throw e;
                }
            } else {
                if (buildMany) {
                    lineSb.append(item.filedName).append(" = ");
                }
                if (funType.contains("strs")) {
                    lineSb.append("{");
                    String[] split = cellVal.substring(1, cellVal.length() - 1).split(",");
                    if (split.length > 0) {
                        buildString(lineSb, split[0]);
                    }
                    for (int i = 1; i < split.length; i++) {
                        String s = split[i];
                        lineSb.append(",");
                        buildString(lineSb, s);
                    }
                    lineSb.append("}");
                } else if ((funType.contains("str"))) {
                    buildString(lineSb, cellVal);
                } else {
                    lineSb.append(cellVal);
                }
                lineSb.append(", ");
            }
        }
    }

    @Override
    public void buildHeadLine0(StringBuilder builder, String saveFileName, TypedHeadInfo info) {
        int i = saveFileName.lastIndexOf('.');
        if (i > 0) {
            saveFileName = saveFileName.substring(i);
        }
        builder.append(saveFileName).append(" = {\n");
    }

    @Override
    public void buildLine(StringBuilder builder, TypedHeadInfo headInfo, String id, LineObj line, boolean buildOne, Map<HeadItem, String> replaceVal) {
        if (headInfo.size() == 0) {
            return;
        }
        builder.append("\t");
        boolean haveID = null != id && id.trim().length() != 0;
        if (haveID) {
            builder.append("[").append(id).append("] = ");
        }
        BuildType type;
        if (headInfo.size() == 2 && buildOne) {
            type = BuildType.one;
        } else {
            type = BuildType.many;
        }
        buildStart(builder, type);

        if (BuildType.many == type && haveID) {
            builder.append("id = ").append(id).append(", ");
        }
        int oldLen = builder.length();

        for (HeadItem item : headInfo) {
            if (item.type.equals(ID_FIELD_NAME)) continue;
            buildLienItem(builder, line, item, type);
        }
        if (type == BuildType.one && builder.length() == oldLen) {
            // 长度不变
            builder.append("\"\"");
        }
        buildEnd(builder, type);

    }

    @Override
    public String getSaveFileName(Sheet sheet, String fileName) {
        if (!fileName.endsWith(Main.clientDataFileNameFix)) {
            return fileName + Main.clientDataFileNameFix;
        }
        return fileName;
    }

    @Override
    public void buildEnd(StringBuilder builder, TypedHeadInfo headInfo) {
        builder.append("};\n");
    }

    @Override
    public HeadItem getIDHeadItem(TypedHeadInfo headInfo) {
        return headInfo.getItemByType(ID_FIELD_NAME);
    }

    @Override
    public void parseHead(String typeAlia, String cellVal, TypeConsumer consumer) {
        parseLuaHead(typeAlia, consumer);
    }
}
